<!-- <template>
  <div>
    <div>
      <a-form class="headerSerch" layout="inline">
        <a-row :gutter="24">
          <a-col :md="5" :sm="24">
            <a-form-item label="单号">
              <a-input v-model="queryParams.sp_no" placeholder="" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="申请人">
              <a-select
                v-model="queryParams.payee"
                show-search
                placeholder="Select a person"
                style="width: 200px"
                :options="userList"
                :filter-option="filterOption"
                @change="handleFilterChange"
              >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="5" :sm="24">
            <a-form-item label="报销金额">
              <a-input v-model="queryParams.total_amount" placeholder="" />
            </a-form-item>
          </a-col>
          <a-col :md="5" :sm="24">
            <a-form-item label="申报日期">
              <a-date-picker v-model="queryParams.declare_date" placeholder="" />
            </a-form-item>
          </a-col>
          <a-col :md="3" :sm="24">
            <a-button v-action:query @click="search" type="primary">查询</a-button>
            <a-button v-action:query @click="reset" type="default">重置</a-button>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="6" :sm="24">
            <a-button
              v-action:add
              style="float: left; margin-top:10px ;"
              @click="showModal()"
              type="primary"
            >新增</a-button
            >
          </a-col>
        </a-row>
      </a-form>

      <a-table
        rowKey="id"
        :columns="columns"
        :data-source="reimbursementList"
        @expandedRowsChange="expandedRowsChange"
        class="components-table-demo-nested"
        :pagination="false"
        :loading="loading"
      >
        <a slot="status" slot-scope="text">
          <a-tag v-if="text == 0" color="#2db7f5">待审核</a-tag>
          <a-tag v-if="text == 1" color="#87d068">已审核</a-tag>
        </a>
        <a slot="operation" slot-scope="text,record">
          <a-button v-action:update @click="showModal(record)" type="primary">编辑</a-button>
          <a-popconfirm
            title="Are you sure delete this record?"
            ok-text="确定"
            cancel-text="取消"
            @confirm="removeReimbursement(record)"
          >
            <a-button v-action:delete type="danger">删除</a-button>
          </a-popconfirm>
        </a>

        <a-table
          slot="expandedRowRender"
          slot-scope="record"
          rowKey="id"
          :columns="innerColumns"
          :data-source="record.reimbursement_items"
          :pagination="false"
        >
        </a-table>
      </a-table>
      <a-pagination
        v-model="queryParams.page"
        :page-size-options="pageSizeOptions"
        :total="total"
        show-size-changer
        :page-size="queryParams.pageSize"
        @showSizeChange="onShowSizeChange"
        @change="changePage"
        class="pagination"
        :show-total="(total, range) => `共${total}条`"
      >
        <template slot="buildOptionText" slot-scope="props">
          <span v-if="props.value !== '50'">{{ props.value }}条/页</span>
        </template>
      </a-pagination>
    </div>
    <AddModal @ok="handleOk" :current="current" :visible="visible" :userList="userList" />
  </div>
</template>

<script>
import AddModal from './addModal.vue'
import request from '@/utils/request'
import { getFormatDate, isNotEmptyList } from '@/utils/util'
// import { ref } from 'vue'

const innerColumns = [
  { title: 'id', dataIndex: 'id', key: 'id' },
  { title: '报销项目', dataIndex: 'project_name', key: 'project_name' },
  { title: '报销金额', dataIndex: 'amount', key: 'amount' },
  { title: '不含税金额', dataIndex: 'no_tax_amount', key: 'no_tax_amount' },
  { title: '税额', dataIndex: 'tax_amount', key: 'tax_amount' },
  {
    title: '发生日期',
    dataIndex: 'occurrence_date',
    key: 'occurrence_date',
    customRender: (text, record) => {
      return getFormatDate(text, 'YYYY-MM-DD')
    }
  }
]
export default {
  name: 'AntdDemo',
  components: {
    AddModal
  },
  data () {
    const columns = [
      { title: '报销单号', dataIndex: 'sp_no', key: 'sp_no' },
      { title: '申请人', dataIndex: 'payee.username', key: 'payee' },
      {
        title: '报销金额',
        dataIndex: 'total_amount',
        key: 'total_amount',
        customRender: (text, record) => {
          return `¥${text}`
        }
      },
      {
        title: '备注',
        dataIndex: 'remark',
        key: 'remark',
        customRender: (text, record) => {
          return (
            <a-tooltip placement="top">
              <template slot="title">
                <span>{text}</span>
              </template>
              <span>{text}</span>
            </a-tooltip>
          )
        }
      },
      {
        title: '申请日期',
        dataIndex: 'declare_date',
        key: 'declare_date',
        customRender: (text, record) => {
          return getFormatDate(text, 'YYYY-MM-DD')
        }
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        scopedSlots: { customRender: 'status' }
      },
      { title: '操作', key: 'operation', scopedSlots: { customRender: 'operation' } }
    ]
    return {
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 }
        }
      },
      formItemLayoutWithOutLabel: {
        wrapperCol: {
          xs: { span: 24, offset: 0 },
          sm: { span: 20, offset: 4 }
        }
      },

      pageSizeOptions: ['2', '5', '10', '20'],
      queryParams: {
        page: 1,
        pageSize: 10
      },
      editingKey: '',
      total: 0,
      form: this.$form.createForm(this, { name: 'reimbursement' }),
      visible: false,
      columns,
      totalAmount: 0,
      loading: false,
      current: undefined,
      innerColumns,
      expandedRowKeys: [],
      reimbursementList: [],
      reimbursementItemList: [],
      cacheData: [],
      userList: []
    }
  },

  beforeCreate () {
    // 创建表单
    this.form = this.$form.createForm(this, { name: 'reimbursement' })
    this.form.getFieldDecorator('keys', { initialValue: [], preserve: true })
  },

  watch: {
    reimbursementItemList (newList, oldList) {
      let totalAmount = 0
      if (newList.length > 0) {
        newList.map((item) => {
          totalAmount = totalAmount + parseFloat(item.no_tax_amount) + parseFloat(item.tax_amount)
        })
        this.totalAmount = totalAmount
      }
    }
  },
  created () {
    this.getReimbursementList(this.queryParams)
    this.getUserList()
  },

  methods: {
    handleFilterChange (value) {
      console.log(`selected ${value}`)
      this.queryParams.payee = value
    },

    filterOption (input, option) {
      // 自定义搜索逻辑，根据关键词匹配文本
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },

    async getUserList () {
      const response = await request.get('/user/')
      if (isNotEmptyList(response.results)) {
        response.results.map((item) => {
          this.userList.push({
            value: item.id,
            label: item.username
          })
        })
      }
    },

    search () {
      this.queryParams.page = 1
      this.getReimbursementList(this.queryParams)
    },

    reset () {
      this.queryParams = {
        page: 1,
        pageSize: this.queryParams.pageSize
      }
      this.getReimbursementList(this.queryParams)
    },

    changePage (current, pageSize) {
      this.queryParams.page = current
      this.getReimbursementList(this.queryParams)
    },

    onShowSizeChange (current, pageSize) {
      this.queryParams.pageSize = pageSize
      this.getReimbursementList(this.queryParams)
    },

    addItem () {
      var itemObj = {
        guid: this.guid(),
        project_name: '',
        no_tax_amount: 0,
        occurrence_date: getFormatDate(new Date(), 'YYYY-MM-DD'),
        tax_amount: 0,
        remark: ''
      }
      this.reimbursementItemList.push(itemObj)
    },

    guid () {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
        var r = Math.random() * 16 || 0
        const v = c === 'x' ? r : r & 0x3 || 0x8
        return v.toString(16)
      })
    },

    addRemoveItem (index) {
      this.reimbursementItemList.splice(index, 1)
    },

    async getReimbursementList (queryParams) {
      this.loading = true
      if (queryParams.declare_date) {
        queryParams.declare_date = getFormatDate(queryParams.declare_date, 'YYYY-MM-DD')
      }
      const response = await request.get(`reimbursement/`, {
        params: queryParams
      })
      if (response) {
        this.reimbursementList = response.results
        this.total = response.count
        this.loading = false
      }
    },

    async getReimbursementById (id) {
      const response = await request.get(`reimbursement/${id}`, {})
      if (response) {
        this.current = response
        this.totalAmount = response.total_amount
        this.reimbursementItemList = response.reimbursement_items
      }
    },

    async updateReimbursementItem (paramas) {
      const response = await request.patch(`reimbursement/item/${paramas.id}`, {
        ...paramas
      })

      return response
    },

    getCurrentDate () {
      return getFormatDate(new Date(), 'YYYY-MM-DD')
    },

    async addReimbursement (paramas) {
      const response = await request.post('reimbursement/', {
        ...paramas
      })
      if (response) {
        this.getReimbursementList(this.queryParams)
      }
    },

    async updateReimbursement (paramas, id) {
      const response = await request.patch(`reimbursement/${id}`, {
        ...paramas
      })
      if (response) {
        this.getReimbursementList(this.queryParams)
      }
    },

    expandedRowsChange (expanded, b, c, d) {
      if (expanded) {
        // console.log('expanded', expanded, b,c,d);
      }
    },
    async removeReimbursement (record) {
      const response = await request.delete(`reimbursement/${record.id}`)
      if (!response) {
        this.$message.success('删除成功')
        this.getReimbursementList(this.queryParams)
      }
    },
    async removeReimbursementItem (itemId) {
      const response = await request.delete(`reimbursement/item/${itemId}`)
      if (!response) {
        this.$message.success('删除成功')
        this.getReimbursementList(this.queryParams)
      }
      return response
    },

    showModal (record) {
      const form = this.form
      if (record) {
        this.current = record
        this.totalAmount = record.total_amount
        this.reimbursementItemList = record.reimbursement_items
        this.cacheData = record.reimbursement_items.map((item) => ({ ...item }))
        this.$nextTick(() => {
          form.setFieldsValue({
            payee: record.payee.id,
            declare_date: getFormatDate(record.declare_date, 'YYYY-MM-DD'),
            // total_amount: record.total_amount,
            remark: record.remark
          })
        })
      }
      this.visible = true
    },

    handleCreateReimbursement () {
      // const form = this.$refs.collectionForm.form;
      const form = this.form
      // values = form.getFieldsValue()
      // console.log('valuesvaluesvalues',values)
      form.validateFields((err, values) => {
        if (err) {
          return
        }

        values.declare_date = getFormatDate(values.declare_date, 'YYYY-MM-DD')
        const reimbursementItemList = this.reimbursementItemList
        for (const item of reimbursementItemList) {
          delete item.guid
        }
        values.reimbursement_items = this.reimbursementItemList

        let response
        if (this.current && this.current.id) {
          const id = this.current.id
          response = this.updateReimbursement(values, id)
          this.$message.success('修改成功')
        } else {
          response = this.addReimbursement(values)
          this.$message.success('添加成功')
        }

        if (response) {
          form.resetFields()
          this.visible = false
          this.current = undefined
        }
      })
    },

    handleCancel () {
      this.form.resetFields()
      this.visible = false
      this.current = undefined
      this.totalAmount = 0
      this.reimbursementItemList = []
    },

    removeItem (itemId) {
      if (this.reimbursementItemList.length === 1) {
        this.$message.info('至少保留一条报销明细！！！')
        return
      }

      const newData = [...this.reimbursementItemList]
      const filterItemList = newData.filter((item) => itemId !== item.id)
      this.reimbursementItemList = filterItemList
      this.removeReimbursementItem(itemId)
    },

    async saveItem (id) {
      const newData = [...this.reimbursementItemList]
      const newCacheData = [...this.cacheData]
      const target = newData.find((item) => id === item.id)
      const targetCache = newCacheData.find((item) => id === item.id)
      if (target && targetCache) {
        delete target.editable
        this.reimbursementItemList = newData
        Object.assign(targetCache, target)
        // 将改变后的值 记录到缓存中去
        this.cacheData = newCacheData
      }
      const response = await this.updateReimbursementItem(target)
      if (response) {
        this.editingKey = ''
        this.$message.success('更新成功')
        this.getReimbursementById(this.current.id)
        this.getReimbursementList(this.queryParams)
      }
    },

    editItem (id) {
      const newData = [...this.reimbursementItemList]
      const target = newData.find((item) => id === item.id)
      this.editingKey = id
      if (target) {
        target.editable = true
        this.reimbursementItemList = newData
      }
    },

    handleChange (value, id, column) {
      const newData = [...this.reimbursementItemList]
      const target = newData.find((item) => id === item.id)
      if (target) {
        target[column] = value
        target.amount = parseFloat(target.no_tax_amount) + parseFloat(target.tax_amount)

        this.reimbursementItemList = newData
      }
    },

    cancelEdit (id) {
      const newData = [...this.reimbursementItemList]
      const target = newData.find((item) => id === item.id)
      this.editingKey = ''

      // 将缓存中的数据还原
      if (target) {
        Object.assign(
          target,
          this.cacheData.find((item) => id === item.id)
        )
        delete target.editable
        this.reimbursementItemList = newData
      }
    }
  }
}
</script>

<style>
.headerSerch {
  padding: 20px;
}
.pagination {
  float: right;
  padding: 40px;
}

.components-table-demo-nested {
  padding: 20px;
}

.dynamic-delete-button {
  cursor: pointer;
  position: relative;
  top: 4px;
  font-size: 24px;
  color: #999;
  transition: all 0.3s;
}
.dynamic-delete-button:hover {
  color: #777;
}
.dynamic-delete-button[disabled] {
  cursor: not-allowed;
  opacity: 0.5;
}
</style> -->
